package com.edu.ocrdemo.controller;

import com.edu.ocrdemo.common.TaskStatus;
import com.edu.ocrdemo.entity.Task;
import com.edu.ocrdemo.repository.TaskRepository;
import com.edu.ocrdemo.service.FileProcessor;
import com.edu.ocrdemo.service.OcrService;
import com.edu.ocrdemo.utils.BatchOcrRequest;
import lombok.AllArgsConstructor;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @Author tfan
 * @Description
 * @Date 2024/12/31 11:55
 **/
@RestController
//@AllArgsConstructor()
public class OcrController {


    @Autowired
    private OcrService ocrService;

    private final TaskRepository taskRepository;
    private final FileProcessor fileProcessor;

    @Value("${ocr.file-max-size}")
    private long maxFileSize;

    public OcrController(TaskRepository taskRepository, FileProcessor fileProcessor) {
        this.taskRepository = taskRepository;
        this.fileProcessor = fileProcessor;
    }

    @PostMapping(value = "/recognize", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String recognizeImage(@RequestParam("file") MultipartFile[] file) throws TesseractException, IOException {
        // 调用OcrService中的方法进行文字识别
        return ocrService.recognizeText(file);
    }

    @PostMapping(value = "/pdf", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> recognizeImage(@RequestParam("file") MultipartFile file) throws TesseractException, IOException {
        if (file.getSize() > maxFileSize * 1024 * 1024) {
            return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body("文件大小不能超过" + maxFileSize + "MB。");
        }
        // TODO 只能上传.pdf文件，需要增加文件类型校验
        // 生成唯一任务 ID
        String taskId = UUID.randomUUID().toString();

        // 创建任务并存储
        Task task = new Task(taskId, TaskStatus.PENDING, null, LocalDateTime.now(), null);
        if (!taskRepository.save(task)) {
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("服务器繁忙，请稍后再试。");
        }

        // 异步处理文件
        ocrService.extractTextFromPDF(taskId, file);
        return ResponseEntity.ok(taskId);
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile[] file) {

        // 生成唯一任务 ID
        String taskId = UUID.randomUUID().toString();

        // 创建任务并存储
        Task task = new Task();
        task.setTaskId(taskId);
        task.setStatus(TaskStatus.PENDING);
        task.setCreatedTime(LocalDateTime.now());
        if (!taskRepository.save(task)) {
            return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body("服务器繁忙，请稍后再试。");
        }

        // 异步处理文件
        fileProcessor.processFile(taskId, file);

        return ResponseEntity.ok(taskId);
    }


    @GetMapping("/{taskId}")
    public ResponseEntity<Task> getTaskStatus(@PathVariable String taskId) {
        Task task = taskRepository.findById(taskId);
        if (task == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(task);
    }
}
